package cn.kow.kmall.core.util;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import lombok.extern.slf4j.Slf4j;

import java.io.InputStream;

/**
 * @Author: lijun
 * @Description:
 * @Date: Created in 2020-06-04 15:14
 * @Modified By:
 */
@Slf4j
public class OSSUtils {

    public static String uploadImage(String path, InputStream inputStream, String fileName) {
        // 1 初始化用户身份信息（secretId, secretKey）。
        String secretId = "AKIDRghtsfaoSq10sXuIOFtLZbQ6brv42cu5";
        String secretKey = "71hCUZQ5YmnbV5bzEE0bf5HFP3SbXFmC";
        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
        // 2 设置 bucket 的区域, COS 地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
        // clientConfig 中包含了设置 region, https(默认 http), 超时, 代理等 set 方法, 使用可参见源码或者常见问题 Java SDK 部分。
        Region region = new Region("ap-guangzhou");
        ClientConfig clientConfig = new ClientConfig(region);
        COSClient cosClient = null;
        try {
            // 3 生成 cos 客户端。
            cosClient = new COSClient(cred, clientConfig);
            // 指定要上传到 COS 上对象键
            String key = path + "/" + generateKey(fileName);
            ObjectMetadata metadata = new ObjectMetadata();
            PutObjectRequest putObjectRequest = new PutObjectRequest("hefa-1256204998", key, inputStream, metadata);
            PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
            return "https://hefa-1256204998.cos.ap-guangzhou.myqcloud.com/" + key;
        } catch (Exception e) {
            log.error("uploadImage fail", e);
            throw e;
        } finally {
            if (cosClient != null) {
                // 关闭客户端(关闭后台线程)
                cosClient.shutdown();
            }
        }
    }

    private static String generateKey(String originalFilename) {
        int index = originalFilename.lastIndexOf('.');
        String suffix = originalFilename.substring(index);
        String key = UUIDUtils.get32UUID() + suffix;
        return key;
    }

}
